<template>
	<view class="wrap">
		<uni-section title="站点信息" titleFontSize="28rpx" titleColor="#212121">
			<template v-slot:decoration>
				<view class="decoration"></view>
			</template>
			<view class="form">
				<uni-forms ref="stationForm" :modelValue="stationFormData" :label-width="78" :rules="rules">
					<uni-forms-item label="站点名称" required name="name">
						<uni-easyinput v-model="stationFormData.name" placeholder="请输入站点名称" />
					</uni-forms-item>
					<uni-forms-item label="使用方" required name="use_company_id">
						<uni-data-select v-model="stationFormData.use_company_id" :localdata="range"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="联系人" required name="first_contacts">
						<uni-easyinput v-model="stationFormData.first_contacts" placeholder="请输入联系人" />
					</uni-forms-item>
					<uni-forms-item label="联系电话" required name="first_contacts_phone">
						<uni-easyinput v-model="stationFormData.first_contacts_phone" placeholder="请输入联系电话" />
					</uni-forms-item>
				</uni-forms>
			</view>
		</uni-section>
		<uni-section title="监控配置" titleFontSize="28rpx" titleColor="#212121">
			<template v-slot:decoration>
				<view class="decoration"></view>
			</template>
			<view class="form">
				<uni-forms ref="cameraForm" :modelValue="cameraFormData" :label-width="80" :rules="rules">
					<uni-forms-item label="监控名称" required name="camera_name">
						<uni-easyinput v-model="cameraFormData.camera_name" placeholder="请输入监控名称" />
					</uni-forms-item>
					<uni-forms-item label="序列号" required name="camera_sn">
						<uni-easyinput v-model="cameraFormData.camera_sn" placeholder="请输入序列号" />
					</uni-forms-item>
					<uni-forms-item label="通道号" required name="camera_channel">
						<uni-easyinput v-model="cameraFormData.camera_channel" placeholder="请输入通道号" />
					</uni-forms-item>
					<uni-forms-item label="验证码" required name="verification_code">
						<uni-easyinput v-model="cameraFormData.verification_code" placeholder="请输入验证码" />
					</uni-forms-item>
				</uni-forms>
			</view>
		</uni-section>
		<view class="btn row j-center a-center" @click="baocun">
			保存
		</view>
	</view>
</template>

<script setup lang="ts" type='module'>
	import { ref } from 'vue'
	import gcoord from 'gcoord';
	import { request } from '@/utils'
	import { onLoad } from '@dcloudio/uni-app'
	import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'
	const stationForm = ref()
	const cameraForm = ref()
	onLoad((options) => {
		stationFormData.value.id = options.id
	})
	const rules = ref({
		name: {
			rules: [{
				required: true,
				errorMessage: '站点名称不能为空'
			}]
		},
		use_company_id: {
			rules: [{
				required: true,
				errorMessage: '请选择使用方'
			}]
		},
		first_contacts: {
			rules: [{
				required: true,
				errorMessage: '联系人不能为空'
			}]
		},
		first_contacts_phone: {
			rules: [
				{
					required: true,
					errorMessage: '联系电话不能为空',
				}, {
					validateFunction: function (rule, value, data, callback) {
						const reg = /^1[3456789]\d{9}$/
						if (!reg.test(value)) {
							callback('请输入合法手机号')
						}
						return true
					}
				}
			]
		},
		camera_name: {
			rules: [{
				required: true,
				errorMessage: '监控名称不能为空'
			}]
		},
		camera_sn: {
			rules: [{
				required: true,
				errorMessage: '序列号不能为空'
			}]
		},
		camera_channel: {
			rules: [{
				required: true,
				errorMessage: '通道号不能为空'
			}]
		},
		verification_code: {
			rules: [{
				required: true,
				errorMessage: '验证码不能为空'
			}]
		},
	})
	const stationFormData = ref({
		name: '',
		use_company_id: '',
		first_contacts: '',
		first_contacts_phone: '',
		latitude: '',
		longitude: '',
		province_id: '',
		city_id: '',
		district_id: '',
		street_id: '',
		area: '',
		address: '',
		id: ''
	})
	const cameraFormData = ref({
		camera_name: '',
		camera_sn: '',
		camera_channel: '',
		verification_code: ''
	})
	const baocun = () => {
		Promise.all([stationForm.value.validate(), cameraForm.value.validate()]).then((res : any) => {
			const mergeArr = [stationFormData.value, cameraFormData.value]
			const mergedObject = mergeArr.reduce((result : any, obj : any) => {
				return { ...result, ...obj };
			}, {});
			console.log(mergedObject);
			uni.showModal({
				title: '提示',
				content: '是否确定保存',
				success: async (res) => {
					if (res.confirm) {
						console.log('用户点击确定');
						const resData : any = await request('/api/v1/addStationAndCameraInfo?permission=miniProgramScanInput', mergedObject, 'POST')
						console.log(resData);
						if(resData.code !== 1000) {
							uni.showToast({
								title: resData.message,
								icon: 'error'
							})
						} else {
							uni.showToast({
								title: '保存成功',
							})
							uni.navigateBack({
								success() {
									uni.$emit('update')
								}
							})
						}
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		})
	}
	const range = ref([])
	const getCompanyList = async () => {
		const res : any = await request('/api/v1/getCompanyList?permission=companyList', { type: 1, isPageSize: 0 }, 'GET')
		range.value = res.data.map((item : any) => {
			return {
				value: item.id,
				text: item.name
			}
		})
	}
	const getLocation = () => {
		const showmap = new QQMapWX({
			key: 'UGXBZ-47EWQ-BKA56-4O5OG-T4T4T-3XFNX'
		});
		// const result = gcoord.transform(
		// 	[118.631372, 32.051972],    // 经纬度坐标
		// 	gcoord.WGS84,               // 当前坐标系
		// 	gcoord.BD09                 // 目标坐标系
		// );
		// console.log(result);

		// showmap.reverseGeocoder({
		// 	location: {
		// 		latitude: 32.086053487472896,
		// 		longitude: 118.66776961162044
		// 	},
		// 	success(result : any) {
		// 		console.log(result);
		// 		const streeInfo = result.result.address_reference.town
		// 		const areaInfo = result.result.address_component
		// 		stationFormData.value.province_id = streeInfo.id.substring(0, 2)
		// 		stationFormData.value.city_id = streeInfo.id.substring(0, 4)
		// 		stationFormData.value.district_id = streeInfo.id.substring(0, 6)
		// 		stationFormData.value.street_id = streeInfo.id
		// 		stationFormData.value.area = `${areaInfo.province}${areaInfo.city}${areaInfo.district}${streeInfo.title}`
		// 		stationFormData.value.longitude = streeInfo.location.lng
		// 		stationFormData.value.latitude = streeInfo.location.lat
		// 		console.log(stationFormData.value);
		// 	}
		// });
		uni.getLocation({
			type: 'gcj02',
			isHighAccuracy: true,
			success(res:any) {
				let { latitude, longitude } = res
				const transformRes = gcoord.transform([longitude, latitude], gcoord.GCJ02, gcoord.BD09)
				// let x = longitude
				// let y = latitude
				// let x_pi = (3.14159265358979324 * 3000.0) / 180.0
				// let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi)
				// let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi)
				// let lngs = z * Math.cos(theta) + 0.0065
				// let lats = z * Math.sin(theta) + 0.006
				showmap.reverseGeocoder({
					location: {
						latitude: latitude,
						longitude: longitude
					},
					success(result : any) {
						// console.log(result);
						// console.log(latitude);
						// console.log(longitude);
						const streeInfo = result.result.address_reference.town
						const areaInfo = result.result.address_component
						stationFormData.value.province_id = streeInfo.id.substring(0, 2)
						stationFormData.value.city_id = streeInfo.id.substring(0, 4)
						stationFormData.value.district_id = streeInfo.id.substring(0, 6)
						stationFormData.value.street_id = streeInfo.id
						stationFormData.value.area = `${areaInfo.province}${areaInfo.city}${areaInfo.district}${streeInfo.title}`
						stationFormData.value.address = result.result.formatted_addresses.standard_address
						stationFormData.value.longitude = transformRes[0]
						stationFormData.value.latitude = transformRes[1]
						console.log(stationFormData.value);
					}
				});
			},
			fail(err) {
				console.log(err);
			}
		})
	}
	getLocation()
	getCompanyList()
</script>

<style scoped lang="scss">
	::v-deep .distraction {
		font-weight: bold;
	}

	::v-deep .uni-forms-item {
		&:last-child {
			margin-bottom: 20rpx;
		}
	}

	::v-deep .uni-section {
		background-color: #F6F6F6;
		margin-bottom: 15rpx;
	}

	.wrap {
		padding: 24rpx;
		background-color: #F6F6F6;
		padding-bottom: 40rpx;
		min-height: 100vh;

		.decoration {
			width: 12rpx;
			height: 22rpx;
			margin-right: 4px;
			border-radius: 4rpx;
			font-weight: bold;
			background: linear-gradient(180deg, #2986F6 0%, #6FABFC 100%);
		}

		.form {
			// height: 368rpx;
			background-color: #ffffff;
			box-shadow: 0px 3px 6px rgba(191, 191, 191, 0.16);
			border-radius: 16rpx;
			padding: 44rpx;
		}

		.btn {
			background-color: #3665FF;
			color: #ffffff;
			height: 88rpx;
			font-size: 34rpx;
			margin-top: 60rpx;
			border-radius: 200rpx;
		}
	}
</style>